package com.midou.administration.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.midou.administration.bo.Msg;
import com.midou.administration.bo.OrderAllBo;
import com.midou.administration.bo.OrderBo;
import com.midou.administration.bo.ToTheNumberOfDays;
import com.midou.administration.entity.*;
import com.midou.administration.mapper.*;
import com.midou.administration.service.OrderService;
import com.midou.administration.utils.QRCodeUtils;
import com.midou.administration.utils.Settlement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author MrChen
 * @since 2021-03-24
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;        //直接注入mapper

    //用户接口
    @Autowired
    private UsersMapper usersMapper;

    //用户卡包接口
    @Autowired
    private UserCouponMapper userCouponMapper;

    //餐桌接口
    @Autowired
    private DeskMapper deskMapper;


    //商家
    @Autowired
    private BusinessMapper businessMapper;

    //消费记录
    @Autowired
    private MemberMapper memberMapper;

    private String staticPath = System.getProperty("user.dir")+"\\midou-restaurant-administration\\src\\main\\resources\\static\\image";

    public Page queryOrder(OrderBo orderBo){
        List<Order> orderList=orderMapper.queryOrder(orderBo.getPage(),orderBo.getBusinessId(),orderBo.getValue1(),orderBo.getValue2(),orderBo.getValue3());
        orderBo.getPage().setRecords(orderList);
        return orderBo.getPage();
    }

    /**
     * 按照商户id查找该商户的所有收入金额
     * @param id
     * @return
     */
    public int doUserIdFindAllPrice(int id){
        int price = orderMapper.doUserIdFindAllPrice(id);
        return price;
    }

    /**
     * 按照商户id查找该商户的所有定单总数
     * @param id
     * @return
     */
    public int doUserIdFindAllOrder(int id){
        int countOrder = orderMapper.doUserIdFindAllOrder(id);
        return countOrder;
    }

    /**
     * 返回最近7天每天的收入
     * @param id
     * @return
     */
    public List<ToTheNumberOfDays> doDayFindAllPrice(int id){
        List<ToTheNumberOfDays> price = this.orderMapper.doDayFindAllPrice(id);
        return price;
    }

    /**
     * 返回最近7天每天的订单量
     * @param id
     * @return
     */
    public List<ToTheNumberOfDays> doDayFindAllOrder(int id){
        List<ToTheNumberOfDays> count = this.orderMapper.doDayFindAllOrder(id);
        return count;
    }

    /**
     * 查询订单信息  返回的订单信息中包含订单详情
     * @param    订单id
     * @return     订单信息
     */
    @Override
    public List<OrderAllBo> queryOrderAndInfoById(Integer orderId) {
        List<OrderAllBo> list = this.orderMapper.queryOrderAndInfoById(orderId);
        for (OrderAllBo orderAllBo : list) {
            orderAllBo.setMenuImg(QRCodeUtils.ImageToBase64ByLocal(staticPath+"\\"+orderAllBo.getMenuImg()));
        }
        return list;
    }

    @Override
    @Transactional
    public Order addDingdan(Order order) {
        int or = this.orderMapper.insert(order);
        /**
         * 根据桌号id更改餐桌状态
         */
        int count = this.deskMapper.updateByidState(order.getDeskId());

        return order;
    }

    /**
     * 结账方法
     * @param settlement 结账类
     * @return  是否结账成功  消息类
     */
    @Override
    @Transactional
    public Msg jiezhang(Settlement settlement) {
        /**
         * 查询订单信息根据订单号1
         * 查询账户信息        1
         * 判断账户金额是否足够 1
         * 根据是否会员进行打折优惠 1
         * 对账户进行更新      1
         * 对订单状态进行更新
         * 添加用户消费记录
         */
        Order order = this.orderMapper.queryOrderByOrderNum(settlement.getOrderNumber());   //根据订单号 查询订单信息
        Users user = this.usersMapper.selectById(settlement.getUserId());
        if(order.getOrderState()==1){
            return new Msg(false,"该订单已经结算完成!");
        }

        //判断支付密码是否输入正确
        if(!user.getUserPaymentCode().equals(settlement.getPwd())){
            return new Msg(false,"支付密码不正确,请重新结账!");
        }

        //判断金额是否足够
        if(user.getUserMoney()<order.getOrderPrice()){
            return new Msg(false,"用户金额不足!请选择其他支付方式。");
        }

        if(settlement.getUcId()!=0){
            System.out.println("使用优惠券进行结账");
            /* 有优惠券 进行价格抵扣 */
            UserCoupon coupon = this.userCouponMapper.sele(settlement.getUcId());
            //判断该优惠券的商家信息 属于不属于该商家
            if(coupon.getUcBId() != order.getBusinessId()){
                return new Msg(false,"该优惠券不能用来进行支付该订单!");
            }

            if(coupon.getUcState() == 1){
                return new Msg(false,"优惠券已经使用过了!");
            }

            //新增消费记录
            Member number = new Member();
            String uuid = UUID.randomUUID().toString();
            uuid = uuid.replaceAll("-","");
            number.setMemCardNumber(uuid);
            number.setMemRechargeTime(new Date());  //操作时间
            Double price = order.getOrderPrice() - coupon.getCoupon().getCePrice(); //应付金额减去  优惠金额  = 支付金额

            //会员在店消费 进行折扣  优惠30
            //最后支付金额 = 支付金额 - 支付金额 * 折扣
            if(user.getUserBusinessId() != order.getBusinessId()){
                price = price - price * user.getUserDiscount();
                System.out.println("是会员最后操作金额是:"+price);
            }

            number.setMemConsumption(price);        //操作金额
            number.setMemBalance(user.getUserMoney() - (order.getOrderPrice() - coupon.getCoupon().getCePrice()));  //操作后的金额
            number.setUserId(user.getUserId());
            number.setClerkId(0);
            this.memberMapper.insert(number);

            //商家营业额进行修改
            int count = this.businessMapper.updateProfit(order.getBusinessId(),(order.getOrderPrice() - coupon.getCoupon().getCePrice()));


            //进行扣款
            user.setUserMoney(user.getUserMoney() - (order.getOrderPrice() - coupon.getCoupon().getCePrice()) );
            this.usersMapper.updateById(user);  //更新用户信息
//            //订单状态更新  状态更新成为已完成
            order.setOrderState(2);
            this.orderMapper.updateStateById(order.getOrderId());

            /* 更改优惠券
            *   改为已使用   2是未使用  1是已经使用
            * */
            coupon.setUcState(1);
            this.userCouponMapper.updateById(coupon);
            /**
             * 更改桌号状态
             * 更改为以带清洁的状态
             * 桌台状态 （ 0 无人状态  1有人 2待清理 3预定)
             */
            Desk desk = this.deskMapper.selectById(order.getDeskId());
            desk.setDeskStatus(3);
            this.deskMapper.updateById(desk);

            return new Msg(true,".....111");
//            消费成功!所使用的优惠券已经使用,请您知晓!
        }
        if(settlement.getUcId()==0){
            /* 没有使用优惠券 */
            //新增消费记录
            Member number = new Member();
            String uuid = UUID.randomUUID().toString();
            uuid = uuid.replaceAll("-","");
            number.setMemCardNumber(uuid);
            number.setMemRechargeTime(new Date());            //操作时间
            number.setMemConsumption(order.getOrderPrice());  //操作金额

            Double price = user.getUserMoney() - order.getOrderPrice();

            if(user.getUserBusinessId() != order.getBusinessId()){
                price = price - price * user.getUserDiscount();
                System.out.println("没有优惠券但是是会员最后操作金额是:" + price);
            }

            number.setMemBalance(price);                    //操作后的金额
            number.setUserId(user.getUserId());
            number.setClerkId(0);
            //添加消费记录
            this.memberMapper.insert(number);

            //商家营业额进行修改
            int count = this.businessMapper.updateProfit(order.getBusinessId(),order.getOrderPrice());

            //进行扣款
            user.setUserMoney(user.getUserMoney() - order.getOrderPrice());

            //更新用户信息
            this.usersMapper.updateById(user);

            //更改支付方式
            order.setOrderPaymentMethod(2);

            //订单状态更新  状态更新成为已完成
            this.orderMapper.updateStateById(order.getOrderId());

            /**
             * 更改桌号状态
             * 更改为以带清洁的状态
             * 桌台状态 （ 0 无人状态  1有人 2待清理 3预定)
             */

            Desk desk = this.deskMapper.selectById(order.getDeskId());
            desk.setDeskStatus(3);
            this.deskMapper.updateById(desk);

            /*
            *
            * */

            return new Msg(true,"消费成功!本次扣款:"+order.getOrderPrice()+"元!请您知晓!");
        }
        return new Msg(false,"正常走入走出");
    }
    public Order seeDeskOrderInfo(Integer did,Integer state){
        QueryWrapper qw = new QueryWrapper();
        qw.eq("desk_id",did);
        qw.eq("order_state",state);
        return orderMapper.selectOne(qw);
    }

}
